//
//  IMWebViewController.m
//  iMobile
//
//  Created by baken on 2016/12/29.
//  Copyright © 2016年 MyApp. All rights reserved.
//

#import "U9WebViewController.h"
#import "U9WebViewProgressView.h"
#import "AppDelegate.h"


@interface U9WebViewController ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>

@property (nonatomic, strong) WKWebView *webView;

@property (nonatomic, strong) U9WebViewProgressView *progressView;

@end

@implementation U9WebViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar addSubview:self.progressView];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.progressView removeFromSuperview];
}


-(void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    if(@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    _webView.UIDelegate = self;
    CGRect navigationBar = self.navigationController.navigationBar.bounds;
    self.progressView = [[U9WebViewProgressView alloc] initWithFrame:CGRectMake(0, navigationBar.size.height - 2, kScreenWidth, 2)];
    [self.navigationController.navigationBar addSubview:self.progressView];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
    //    if (self.hiddenShareButton) {
    self.navigationItem.rightBarButtonItems = nil;
    //    }
    
}

-(WKWebView *)webView{
    if (!_webView) {
        _webView = [[WKWebView alloc] initWithFrame:self.view.frame];
        _webView.navigationDelegate = self;
        _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _webView.UIDelegate = self;
        _webView.allowsBackForwardNavigationGestures = YES;
        _webView.configuration.allowsInlineMediaPlayback = YES;
        _webView.configuration.allowsPictureInPictureMediaPlayback = YES;;
        
        [_webView.configuration.userContentController addScriptMessageHandler:self name:@"OCCompleteHandle"];
        [_webView.configuration.userContentController addScriptMessageHandler:self name:@"getMyAccount"];
        [_webView addObserver:self
                   forKeyPath:@"estimatedProgress"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
        
        [self.view addSubview:_webView];
        
    }
    return _webView;
}


//webview加载urlrequest后，这个方法决定是同意加载或者取消
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSLog(@"-------decidePolicyForNavigationAction");
    NSLog(@"%@",[webView.URL absoluteString]);
    NSLog(@"%@",navigationAction.request);
    if ([[navigationAction.request.URL absoluteString] containsString:@"itunes.apple.com"]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL options:[NSDictionary dictionary] completionHandler:^(BOOL success) {
        }];
        
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

//导航开始(页面加载开始？)
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
    NSLog(@"-------didStartProvisionalNavigation");
    NSLog(@"%@",[webView.URL absoluteString]);
}

//webview接收到服务器respones之后，这个方法决定同意或者取消加载
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    NSLog(@"-------decidePolicyForNavigationResponse");
    NSLog(@"%@",[webView.URL absoluteString]);
    decisionHandler(WKNavigationResponsePolicyAllow);
    
}

//当内容返回时调用 content starts arriving for the main frame
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}



- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
}

//接收到服务器重定向请求的时候
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
}



- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    
    
}



- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    // js 里面的alert实现，如果不实现，网页的alert函数无效
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
                                                        style:UIAlertActionStyleCancel
                                                      handler:^(UIAlertAction *action) {
                                                          completionHandler();
                                                      }]];
    
    [self presentViewController:alertController animated:YES completion:^{}];
    
}

-(void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          completionHandler(YES);
                                                      }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
                                                        style:UIAlertActionStyleCancel
                                                      handler:^(UIAlertAction *action) {
                                                          completionHandler(NO);
                                                      }]];
    
    [self presentViewController:alertController animated:YES completion:^{}];
    
    
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webView.estimatedProgress;
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
    }
    
}


- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    
    NSLog(@"didReceiveScriptMessage %@",message);
}


-(BOOL)prefersStatusBarHidden{
    return UIStatusBarStyleLightContent;
}



@end
